package com.cungmua.app.activity;

import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cungmua.app.R;
import com.cungmua.app.adapter.CartItemAdapter;
import com.cungmua.app.base.BaseDrawerActivitys;
import com.cungmua.app.handler.CartInfoHandler;
import com.cungmua.app.handler.CartItemSelectedHandler;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.CartInfoItem;
import com.cungmua.app.model.CartItem;
import com.cungmua.app.model.request.CartInfoRequest;
import com.cungmua.app.model.response.CartInfoResponse;
import com.cungmua.app.task.CartInfoTask;
import com.cungmua.app.utils.AppUtils;
import com.cungmua.app.view.ExpandableHeightListView;

import java.util.List;

/**
 * Created by kelvin.nguyen on 6/25/14.
 */
public class YourCartActivity extends BaseDrawerActivitys implements CartItemSelectedHandler, CartInfoHandler {

    private ExpandableHeightListView listSKU;
    CartItemAdapter adapter;
    private TextView txtBonusPoint;
    private TextView txtTotal;
    private TextView txtShipPrice;
    private TextView txtPrice;
    private LinearLayout cartEmpty;
    private Button btnBuy;
    private Button btnHome;
    private List<CartInfoItem> itemList;
    private String priceString = "";
    private ImageView icon_home;
    private Button icon_cart;
    private LinearLayout btnCart;

    @Override
    public int getLayoutResource() {
        return R.layout.activity_your_cart;
    }

    @Override
    public void updateView() {
        Cart currentCart = getCurrentCart();
        adapter = new CartItemAdapter(this, this, currentCart.getItems());
        listSKU.setAdapter(adapter);
        updatePrice();
    }

    public void updatePrice() {

        Cart currentCart = getCurrentCart();
        CartInfoRequest request = new CartInfoRequest(getDeviceId(), getToken());
        request.setUserId(getCurrentUser().getId());
        request.setCityId(getCurrentCity().getId());
        request.setProductList(currentCart.toString());

        CartInfoTask task = new CartInfoTask(this, this);

        if (!currentCart.toString().isEmpty()) {
            task.execute(request);
            cartEmpty.setVisibility(View.GONE);
        }else {
            cartEmpty.setVisibility(View.VISIBLE);
            icon_cart.setVisibility(View.GONE);
            //resetPriceFields();
        }
    }


    @Override
    public void loadControls(Bundle savedInstanceState) {
        txtBonusPoint = (TextView) findViewById(R.id.txtBonusPoint);
        txtTotal = (TextView) findViewById(R.id.txtTotal);
        txtShipPrice = (TextView) findViewById(R.id.txtShipPrice);
        txtPrice = (TextView) findViewById(R.id.txtPrice);
        cartEmpty=(LinearLayout)findViewById(R.id.cartEmpty);

        icon_home=(ImageView)findViewById(R.id.icon_home);
        icon_cart=(Button)findViewById(R.id.icon_cart);
        btnHome=(Button)findViewById(R.id.btnHome);
        btnCart=(LinearLayout)findViewById(R.id.btnCart);


        Cart currentCart=getCurrentCart();
        icon_cart.setText(currentCart.getTotalQuantity()+"");

        icon_home.setOnClickListener(new ImageView.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMenu();
            }
        });

        btnCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToYourCart();
            }
        });
        btnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToHotDeal(true);
            }
        });


        listSKU = (ExpandableHeightListView) findViewById(R.id.listSKU);
        listSKU.setExpanded(true);
        listSKU.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);

        listSKU.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode actionMode, int pos, long id, boolean checked) {
            }

            /**
             * Called when action mode is first created. The menu supplied will be used to
             * generate action buttons for the action mode.
             *
             * @param mode ActionMode being created
             * @param menu Menu used to populate action buttons
             * @return true if the action mode should be created, false if entering this
             * mode should be aborted.
             */
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                return false;
            }

            /**
             * Called to report a user click on an action button.
             *
             * @param mode The current ActionMode
             * @param item The item that was clicked
             * @return true if this callback handled the event, false if the standard MenuItem
             * invocation should continue.
             */
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode actionMode) {
            }
        });

        btnBuy = (Button) findViewById(R.id.btnBuy);

        btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToMakeOrder(priceString);
            }
        });
    }

    public void deleteSelectedItems(CartItem item) {
//        List<CartItem> selectedItems = new ArrayList<CartItem>();
//
//        SparseBooleanArray checked = listSKU.getCheckedItemPositions();
//        for (int i = 0; i < checked.size(); i++) {
//            if (checked.valueAt(i))
//                selectedItems.add(adapter.getItem(checked.keyAt(i)));
//        }

        Cart currentCart = getCurrentCart();
//        adapter.getDataSource().removeAll(selectedItems);
        adapter.getDataSource().remove(item);
        adapter.notifyDataSetChanged();

        currentCart.setItems(adapter.getDataSource());

        setCurrentCart(currentCart);


        icon_cart.setText(currentCart.getTotalQuantity()+"");


        updatePrice();
    }

    @Override
    public void onCartItemSelected(CartItem item) {
        Cart currentCart = getCurrentCart();
        boolean changed = false;
        for (CartItem ci : currentCart.getItems()) {
            if (ci.getProductId() == item.getProductId() && ci.getSkuId() == item.getSkuId()) {
                if (ci.getQuantity() != item.getQuantity()) {
                    changed = true;
                }
                ci.setQuantity(item.getQuantity());
            }
        }
        setCurrentCart(currentCart);
        if (changed)
            updatePrice();
    }

    @Override
    public void onBackDealDetails(int id) {
        goToDealDetail(id);
    }

    @Override
    public void onCartInfoReceived(CartInfoResponse response) {
        if (response.getCode() == 0) {
            if (response.getData().getBonusUsed().contains("0")){
                txtBonusPoint.setText("-" + AppUtils.getFullPriceString(Integer.parseInt(response.getData().getBonusUsed())) + "đ");
            } else {
                txtBonusPoint.setText(response.getData().getBonusUsed());
            }
            if (response.getData().getShippingFee().contains("0"))
                txtShipPrice.setText(getString(R.string.full_price_string,
                        AppUtils.getFullPriceString(Integer.parseInt(response.getData().getShippingFee()))));
            else
                txtShipPrice.setText(response.getData().getShippingFee());
            priceString = getString(R.string.full_price_string,
                    AppUtils.getFullPriceString(response.getData().getTotalPrice()));
            txtTotal.setText(priceString);

            int price = 0;
            for (int i=0;i<response.getData().getItemList().size();i++)
                price = price + response.getData().getItemList().get(i).getPrice();
            txtPrice.setText(getString(R.string.full_price_string,
                    AppUtils.getFullPriceString(response.getData().getSumPrice())));
        } else if (response.getCode() == 1000) {
            resetPriceFields();
        }
        Cart currentCart=getCurrentCart();
        icon_cart.setText(currentCart.getTotalQuantity()+"");
    }

    public void resetPriceFields() {
        txtBonusPoint.setText("--");
        txtShipPrice.setText(getString(R.string.free));

        String priceString = getString(R.string.full_price_string,
                AppUtils.getFullPriceString(0));
        txtTotal.setText(priceString);
        btnBuy.setVisibility(View.INVISIBLE);
        txtPrice.setText(priceString);


    }
}

